<?php

class Home extends CI_Controller {

    public $berita;

    function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->model('Model_berita');
        $this->load->model('Model_donatur');
        $this->load->model('Model_mahasiswa');
        
        $prefs['template'] = '

           {table_open}<table align="center" border="0" cellpadding="0" cellspacing="0">{/table_open}

           {heading_row_start}<tr>{/heading_row_start}

           {heading_previous_cell}<th><a href="{previous_url}">&lt;&lt;</a></th>{/heading_previous_cell}
           {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
           {heading_next_cell}<th><a href="{next_url}">&gt;&gt;</a></th>{/heading_next_cell}

           {heading_row_end}</tr>{/heading_row_end}

           {week_row_start}<tr>{/week_row_start}
           {week_day_cell}<td class="dayname" width="30px">{week_day}</td>{/week_day_cell}
           {week_row_end}</tr>{/week_row_end}

           {cal_row_start}<tr>{/cal_row_start}
           {cal_cell_start}<td>{/cal_cell_start}

           {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
           {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today}

           {cal_cell_no_content}{day}{/cal_cell_no_content}
           {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}

           {cal_cell_blank}&nbsp;{/cal_cell_blank}

           {cal_cell_end}</td>{/cal_cell_end}
           {cal_row_end}</tr>{/cal_row_end}

           {table_close}</table>{/table_close}
        ';
        
        
        $this->load->library('calendar',$prefs);
        $query = $this->db->get('berita', 5, 0);
        if ($query->num_rows() > 0) {
            $this->berita = $query->result_array();
        }
    }

    function index() {
        $this->utama();
    }

    function utama() {
        $this->load->view('user_header_view');
        $this->load->view('utama');
        $this->load->view('user_footer_view');
    }

	function list_berita(){
		$data_berita = $this->Model_berita->select_all();
		$data['list_berita']=$data_berita->result_array();
		$this->load->view('user_header_view');
        $this->load->view('summary_berita',$data);
        $this->load->view('user_footer_view');
	}
	
	function detil_berita($id){
		$data['berita'] = $this->Model_berita->selectbyid($id);
		$this->load->view('user_header_view');
        $this->load->view('detil_berita',$data);
        $this->load->view('user_footer_view');
	}
	
    function login() {
        $username = $this->input->post('username');
        $password = md5($this->input->post('password'));
        $result = $this->Model_donatur->login($username, $password);
        if ($result) {
            $result = $this->Model_donatur->select(array('username' => $username));
            $data = array(
                'Loggedin' => TRUE,
                'Role' => 'donatur',
                'Nama' => $result[0]['nama'],
                'ID' => $result[0]['iddonatur']
            );
            $this->session->set_userdata($data);
            redirect(base_url().'home/profil_donatur/'.$data['ID']);
        } else {
            redirect(base_url() . 'home/login_form/1');
        }
    }
	
    function login_form($error=0) {
		
		if($error==1){
			$display['is_error']=true;
		}else{
			$display['is_error']=false;
		}
        $this->load->view('user_header_view');
        $this->load->view('login_form',$display);
        $this->load->view('user_footer_view');
    }

    function logo_korporat(){
        $data['jenis'] = "badan";
        $display['data'] = $this->Model_donatur->select($data);
        $this->load->view('user_header_view');
        $this->load->view('logo_korporat',$display);
        $this->load->view('user_footer_view');
    }
	
    function logout() {
        $newdata = array('Loggedin' => FALSE, 'Nama' => '');
        $this->session->unset_userdata($newdata);
        redirect(base_url());
    }

    function daftar() {
        $data['pesan'] = "Silakan isi form dibawah untuk mendaftar sebagai donatur";
        $this->load->view('user_header_view');
        $this->load->view('form_daftar', $data);
        $this->load->view('user_footer_view');
    }

    function proses_daftar() {
        $data['nama'] = $this->input->post('nama');
        $data['email'] = $this->input->post('email');
        $data['pekerjaan'] = $this->input->post('pekerjaan');
        $data['jenis'] = $this->input->post('jenis');
        $data['alamat'] = $this->input->post('alamat');
        $data['nohp'] = $this->input->post('nohp');
        $data['saldo'] = $this->input->post('saldo');
		$data['rekening'] = $this->input->post('norek');
		$data['bank'] = $this->input->post('bank');
		
        if($data['nama'] == '' || $data['email'] == '' || $data['pekerjaan'] == '' || $data['alamat'] == '' || $data['nohp'] == '' || $data['saldo'] == '') {
            $data['pesan'] = 'Harap isi data dengan lengkap, <a href="#" onclick="back()">kembali</a>';
        }else{
            $data['status']='New';
            $this->db->insert('donatur', $data);
            $subject = '[Beasiswa ITB] Notifikasi Pembuatan Akun';
            $isi = 'Terima kasih telah mendaftar sebagai donatur beasiswa ITB';
            $this->kirim_mail($email, $subject, $isi);
            $this->notify_admin($nama);
            $data['pesan'] = 'Pendaftaran anda telah kami terima, kami akan mengirimkan konfirmasi ke alamat email anda untuk pemberitahuan berikutnya';
        }
        $this->load->view('user_header_view');
        $this->load->view('hal_pesan', $data);
        $this->load->view('user_footer_view');
    }

    function view_berita($idberita) {
        $berita = $this->Model_berita->selectbyid($idberita);
        $this->load->view('user_header_view');
        $this->load->view('view_berita', $berita);
        $this->load->view('user_footer_view');
    }

    function daftar_fakultas() {
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $this->load->view('user_header_view');
            $this->load->view('daftar_fakultas');
            $this->load->view('user_footer_view');
        } else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }

    function daftar_mahasiswa($fakultas) {
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $data['right'] = $data['left'] = false;
            $where = array('fakultas' => $fakultas);
            if ($this->input->post('angkatan') != '' && $this->input->post('angkatan') != '-' ) {
                $data['angkatan'] = $this->input->post('angkatan');
            }
            else
                $data['angkatan'] = '-';
            $data['row'] = $this->Model_mahasiswa->select_mahasiswa_fakultas($where);
            $data['fakultas'] = $fakultas;
            $this->load->view('user_header_view');
            $this->load->view('daftar_mahasiswa', $data);
            $this->load->view('user_footer_view');
        }else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }

    function profil_mahasiswa($id) {
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $where = array('idmhs' => $id);
            $row = $this->Model_mahasiswa->select($where, '', '');
            $data['row'] = $row[0];
            $beasiswa = $this->db->query('SELECT MAX(semester) AS smstr FROM donasi WHERE idmhs=' . $id);
            $result = $beasiswa->result_array();
            $data['beasiswa'] = $result[0]['smstr'];
            $beasiswa = $this->db->get_where('donasi', array('idmhs' => $id));
            $data['beasiswa_donasi'] = $beasiswa->result_array();
            if ($data['row']['statustunda'] == 't')
                $semester = $data['row']['semester'] - 2;
            else
                $semester = $data['row']['semester'] - 1;
            if ($data['beasiswa'] != null) {
                $semester2 = $data['beasiswa'];
            }
            else
                $semester2 = 0;
            if ($semester >= $semester2)
                $data['semester'] = $semester;
            else
                $data['semester'] = $semester2;
            $data['sisa'] = $data['semester'] + 1;
            $this->load->view('user_header_view');
            $this->load->view('profil_mahasiswa', $data);
            $this->load->view('user_footer_view');
        }else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }

    function donasikan() {
        $mulai = $_POST['sisa'];
        $idmhs = $_POST['idmhs'];
        $spp = $_POST['spp'];
        $iddonatur = $this->session->userdata('ID');
        $strpesan = ' ';
        for ($i = $mulai; $i < 9; $i++) {
            $str = 'semester' . $i;
            if (isset($_POST[$str])) {
                $query = $this->db->get_where('donatur', array('iddonatur' => $iddonatur))->result_array();
                if ($query[0]['saldo'] >= $spp) {
                    $data = array(
                        'iddonatur' => $iddonatur,
                        'idmhs' => $idmhs,
                        'semester' => $i
                    );
                    $this->db->insert('donasi', $data);
                    $strquery = 'update mahasiswa set slotbeasiswa=slotbeasiswa-1 where idmhs=' . $idmhs;
                    $this->db->query($strquery);
                    $strquery = 'update donatur set saldo=saldo-' . $spp . ' where iddonatur=' . $iddonatur;
                    $this->db->query($strquery);
                    $updatestatus = 'update mahasiswa set statustunda=FALSE where idmhs=' . $idmhs;
                    $this->db->query($updatestatus);
                } else {
                    $strpesan = $strpesan . 'Saldo anda kurang untuk membayar SPP semester ' . $i . '<br/>';
                }
            }
        }
        $data['pesan'] = $strpesan . 'Terima kasih atas sumbangan anda';
        $this->load->view('user_header_view');
        $this->load->view('hal_pesan', $data);
        $this->load->view('user_footer_view');
    }

    function cpdonatur($id='') {
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $id=$this->session->userdata('ID');
            $donatur = $this->Model_donatur->selectbyid($id);
            $display['data'] = $donatur[0];
            $this->load->view('user_header_view');
            $this->load->view('form_edit', $display);
            $this->load->view('user_footer_view');
        } else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }

    function proses_update() {
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $password = $this->input->post('password');
            $id = $this->input->post('iddonatur');
            if ($password == '') {
                unset($_POST['password']);
            } else {
                $_POST['password'] = md5($_POST['password']);
            }
            $this->db->where('iddonatur', $_POST['iddonatur']);
            $this->db->update('donatur', $_POST);
            $this->session->set_userdata(array('Nama' => $_POST['nama']));
            redirect(base_url() . 'home/profil_donatur/'. $_POST['iddonatur'] . '/edited');
        } else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }

    function update_sukses() {
        $data['pesan'] = 'Profil anda telah diubah';
        $this->load->view('user_header_view');
        $this->load->view('hal_pesan', $data);
        $this->load->view('user_footer_view');
    }

    function tambah_donasi() {
        $data['pesan'] = "Masukkan besaran donasi yang ingin anda tambahkan";
        $this->load->view('user_header_view');
        $this->load->view('tambah_donasi', $data);
        $this->load->view('user_footer_view');
    }

    function tambah() {
        //Di sini akan ada fungsi untuk mengirim email ke kedua pihak. Kepada donatur berisi tata cata penambahan, kepada admin untuk bsa dicek siapa
        $data['pesan'] = 'Penambahan donasi anda akan diproses, cek email untuk pemberitahuan berikutnya';
        $iddonatur = $this->session->userdata('ID');
        $jumlah_tambahan = $this->input->post('jumlah_tambahan');
        $rekening = $this->input->post('rekening');
        $bank = $this->input->post('bank');
        $row = $this->Model_donatur->selectbyid($iddonatur);
        $this->Model_donatur->insert_tambah_donasi(date("Y-m-d"), $iddonatur, $jumlah_tambahan, "Requested", $rekening, $bank);
        $tujuan1 = $row[0]['email'];
        $nama1 = $row[0]['nama'];
        $subject1 = "[Beasiswa ITB]Penambahan Donasi";
        $isi1 = "Untuk menambah donasi anda, silakan transfer ke rekening 879879878";
        $this->kirim_mail($tujuan1, $subject1, $isi1);
        
        $tujuan2='muhammad.fazri@comlabs.itb.ac.id';
        $subject2 = "[Beasiswa ITB]Notifikasi Penambahan Donasi";
        $isi2 = "User " . $nama1 . " telah request untuk menambah donasinya";
        $this->kirim_mail($tujuan2, $subject2, $isi2);
        redirect(base_url().'home/tambah2');
    }

    function tambah2() {
        $data['pesan'] = 'Penambahan donasi anda akan diproses, cek email untuk pemberitahuan berikutnya';
        $this->load->view('user_header_view');
        $this->load->view('hal_pesan', $data);
        $this->load->view('user_footer_view');
    }

    function kirim_mail($tujuan, $subject, $isi) {
//        $this->load->library('email');
//        
//        $config['protocol'] = 'smtp';
//        $config['smtp_host'] = 'mx2.itb.ac.id';
//        $config['smtp_port'] = 25;
//        
//        $config['charset'] = 'iso-8859-1';
//        $config['wordwrap'] = TRUE;
//        $this->email->initialize($config);
//        
//        $this->email->from('muhammad.fazri@comlabs.itb.ac.id','Admin');
//        $this->email->to($tujuan); 
//        
//        $this->email->subject($subject);
//        $this->email->message($isi);	
//
//        $this->email->send();
        
    }

    function notify_admin($nama){
        $config['protocol'] = 'smtp';
        $config['smtp_host'] = 'mx2.itb.ac.id';
        $config['smtp_port'] = 25;
        
        $config['charset'] = 'iso-8859-1';
        $config['wordwrap'] = TRUE;
        $this->email->initialize($config);
        
        $this->email->to('muhammad.fazri@comlabs.itb.ac.id'); 
        $subject = '[Notifikasi Pembuatan Akun]';
        $isi = 'Calon donatur bernama '.$nama.' baru saja mendaftar, silakan diproses';
        
        $this->email->subject($subject);
        $this->email->message($isi);	

        $this->email->send();
        
    }
    
    function tampil_list_mahasiswa() {
        $id = $this->session->userdata("ID");
        $data['row'] = $this->Model_mahasiswa->tampil_list_mahasiswa($id);
        $array['iddonatur'] = $id;
        $data['row2'] = $this->Model_donatur->select_tambah_donasi($array);
        $this->load->view('user_header_view');
        $this->load->view('tampil_list_mahasiswa', $data);
        $this->load->view('user_footer_view');
    }
    
    function list_news($page=''){
        if($page==''){
            $page=1;
        }
        $data['page']=$page;
        $page=5*($page-1);
        $query=$this->db->get('berita',5,$page);
        $num=$this->db->count_all_results('berita');
        $data['num']=$this->round_up($num,5);
        $data['news']=$query->result_array();
        $this->load->view('user_header_view');
        $this->load->view('list_news', $data);
        $this->load->view('user_footer_view');
    }
    
    function round_up($x,$y){
        $m=$x/$y;
        if($x%$y>0){
            return $m+1;
        }else{
            return $m;
        }
    }
    
    function profil_donatur($id='',$edited='')
    {
        $display['pesan'] = '';
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $id=$this->session->userdata('ID');
            $donatur = $this->Model_donatur->selectbyid($id);
            $display['data'] = $donatur[0];
            if ($edited=='edited')
                $display['pesan'] = 'Profil anda telah diubah';
            $this->load->view('user_header_view');
            $this->load->view('profil_donatur', $display);
            $this->load->view('user_footer_view');
        } else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }
    function edit_foto_form ($id='')
    {
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $id=$this->session->userdata('ID');
            $donatur = $this->Model_donatur->selectbyid($id);
            $display['data']=$donatur[0];
            $this->load->view('user_header_view');
            $this->load->view('form_edit_foto',$display);
            $this->load->view('user_footer_view');
        } else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }
    
    function proses_update_foto() {
        if ($this->session->userdata('Loggedin') == TRUE && $this->session->userdata('Role') == 'donatur') {
            $id=$this->session->userdata('ID');
            $donatur = $this->Model_donatur->selectbyid($id);
            //$base_url_foto = str_replace("/","\\",base_url());
            //echo $base_url_foto."|".  base_url();
            unlink("image/profil/".$donatur[0]['foto']);
            $nama_foto = date("YmdHis").$_FILES["foto"]["name"];
            print_r($_FILES);
            if ($_FILES["foto"]["error"] > 0)
                echo "Return Code: " . $_FILES["foto"]["error"] . "<br />";
            else
                 move_uploaded_file($_FILES["foto"]["tmp_name"], "image/profil/" . $nama_foto);
            $array['foto'] = $nama_foto;
            $this->db->where('iddonatur', $id);
            $this->db->update('donatur', $array);
            redirect(base_url() . 'home/profil_donatur/'. $id . '/edited');
        } else {
            $data['pesan'] = "";
            $this->load->view('user_header_view');
            $this->load->view('login_error', $data);
            $this->load->view('user_footer_view');
        }
    }
}